package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.DimJoinFunction;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.HbaseUtil;
import com.atguigu.gmall.realtime.utils.RedisUtil;
import io.lettuce.core.api.StatefulRedisConnection;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import org.apache.hadoop.hbase.client.AsyncConnection;

import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author Felix
 * @date 2023/12/29
 * 发送异步请求进行维度关联的模板类
 */
public abstract class DimAsyncFunction<T> extends RichAsyncFunction<T, T> implements DimJoinFunction<T> {

    private String tableName;
    private StatefulRedisConnection<String, String> asyncRedisConn;
    private AsyncConnection asyncHbaseConn;

    public DimAsyncFunction(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        asyncRedisConn = RedisUtil.getAsyncRedisConnection();
        asyncHbaseConn = HbaseUtil.getAsyncConnection();
    }

    @Override
    public void close() throws Exception {
        RedisUtil.closeAsyncRedisConnection(asyncRedisConn);
        HbaseUtil.closeAsyncConnection(asyncHbaseConn);
    }

    @Override
    public void asyncInvoke(T obj, ResultFuture<T> resultFuture) throws Exception {
        //创建异步编排对象  ，有返回值(会将当前异步任务执行结果作为参数，传递给下一个异步任务)
        CompletableFuture
            .supplyAsync(
                new Supplier<JSONObject>() {
                    @Override
                    public JSONObject get() {
                        //先根据主键到Redis缓存中获取对应的维度数据---异步
                        JSONObject dimJsonObj = RedisUtil.asyncGetDimInfo(asyncRedisConn, tableName.toLowerCase() + ":" + getKey(obj));
                        return dimJsonObj;
                    }
                }
            )
            //执行异步线程任务      有入参(上一个异步任务的返回值，就是当前任务的入参)，有返回值
            .thenApplyAsync(
                new Function<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject apply(JSONObject dimJsonObj) {
                        if(dimJsonObj == null){
                            System.out.println("~~从hbase中查询"+tableName+"的"+getKey(obj)+"维度~~");
                            //如果从redis中没有找到对应的维度，发送请求到hbase中查询维度数据--异步
                            dimJsonObj = HbaseUtil.getDimInfoFromHbaseByAsync(asyncHbaseConn, GmallConfig.HBASE_NAMESPACE,tableName,getKey(obj));
                            //并将查询出的维度放到Redis中缓存起来 --异步
                            if(dimJsonObj != null){
                                RedisUtil.asyncWriteDim(asyncRedisConn,tableName.toLowerCase() + ":" + getKey(obj),dimJsonObj);
                            }
                        }else{
                            System.out.println("~~从redis中查询"+tableName+"的"+getKey(obj)+"维度~~");
                        }
                        return dimJsonObj;
                    }
                }
            )
            //执行异步线程任务      有入参(上一个异步任务的返回值，就是当前任务的入参)，无返回值
            .thenAcceptAsync(
                new Consumer<JSONObject>() {
                    @Override
                    public void accept(JSONObject dimJsonObj) {
                        if(dimJsonObj != null){
                            //将维度相关的属性补充到流中的对象---异步
                            join(obj,dimJsonObj);
                        }
                        //将补充后的维度发送到下游去 获取数据库交互的结果并发送给 ResultFuture 的 回调 函数
                        resultFuture.complete(Collections.singleton(obj));
                    }
                }
            );
    }

    // 如果异步超时,会执行这个方法
    @Override
    public void timeout(T input, ResultFuture<T> resultFuture) throws Exception {
        // 根据自己情况进行处理
        throw new RuntimeException("异步超时:一般是其他原因导致的异步超时, 请检查: \n" +
            "1.检查集群是否都 ok: hdfs redis hbase kafka. \n" +
            "2.检查下 redis 的配置 bind 0.0.0.0 \n" +
            "3.检查用到的6张维度表是否都在,并且每张表都数据. 最好通过 maxwell-bootstrap 同步一下 \n" +
            "4.找我" +
            "");
    }

}
